<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="staffPhoto" :src="staffPhoto" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <el-progress
      v-if="process"
      type="line"
      :percentage="percentage"
    ></el-progress>
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID2wd7NOGzXv89wUoshHdl04vYyBAvVs33',
  SecretKey: 'rTr1yhFbjeMq56tRlqgIgsqb7TnyvdAd'
})
export default {
  name: 'UploadImg',
  props: {
    staffPhoto: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // imageUrl: '',
      percentage: 0,
      process: false
    }
  },
  methods: {
    upload (params) {
      console.log(params.file)
      if (params.file) {
        this.process = true
        cos.putObject({
          Bucket: 'zh-1308304219', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: params.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          setTimeout(() => {
            this.process = false
            this.percentage = 0
            // this.imageUrl = `https://${data.Location}`
            this.$emit('update:staff-photo', `https://${data.Location}`)
          }, 1000)
        })
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
